package com.base.server.common.utils;

import com.base.server.common.config.RedisClient;
import com.base.server.common.config.jwt.JwtUtil;
import com.base.server.common.constant.Constant;
import com.base.server.modules.user.entity.UserInfo;
import com.base.server.modules.user.entity.UserInfoVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Objects;

/**
 * 描述：获取当前登录用户工具类
 * <p>
 * 作者：Ostrich Hu
 * 时间：2020/1/17 13:58 星期五
 */
@Component
public class UserUtils {

    @Autowired
    private RedisClient redisClient;

    private static RedisClient redis;

    @PostConstruct
    public void init() {
        redis = redisClient;
    }

    public static UserInfoVo getUserInfo() {
        UserInfoVo user = new UserInfoVo();
        if (Objects.nonNull(SecurityUtils.getSubject())) {
            String claim = JwtUtil.getClaim(SecurityUtils.getSubject().getPrincipal().toString(), Constant.JWT.ACCOUNT);
            String str = (String) redis.get(Constant.RedisConstant.PREFIX_TOKEN_U_CACHE + claim);
            Map<String, String> map = (Map) JsonUtils.jsonToMap(str);
            user.setId(map.get("id"));
            user.setLoginName(map.get("loginName"));
            user.setRoleId(map.get("roleId"));
            user.setGroupId(map.get("groupId"));
        }
        return user;
    }

    public static String getUid() {
        return getUserInfo().getId();
    }

}
